package cn.ulyer.core.secure;

import cn.ulyer.common.oauth.OauthClient;
import cn.ulyer.core.domain.ClientInfo;
import cn.ulyer.core.service.ClientInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Component;

@Component
public class OauthClientService implements ClientDetailsService {

    ClientInfoService clientInfoService;

    @Autowired
    public OauthClientService(ClientInfoService clientInfoService){
        this.clientInfoService = clientInfoService;
    }

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        ClientInfo clientInfo = clientInfoService.getById(clientId);
        if(clientInfo == null){
            throw new InvalidClientException("client not found for client_id "+clientId);
        }
        OauthClient client = new OauthClient();
        BeanUtils.copyProperties(clientInfo,client);
        return client;
    }

}
